import filetype
from rest_framework.parsers import JSONParser
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework import status
from django.http import HttpResponse, JsonResponse
from utils.unique_str import get_unique_str
import os
from xfz import settings
from urllib.parse import urljoin

from .forms import *
from .serializers import *
from .models import *
from apps.dog.serializers import FileSerializer
from apps.dog.serializers import FileSerializer


# Create your views here.

@csrf_exempt
@api_view(['GET', 'POST'])
def test1(request):
    if request.method == 'GET':
        return HttpResponse("get OK")

    name = request.POST.get('name')
    file = request.FILES.get('file')
    book = Book.objects.create(
        name=name,  file=file)  # 将数据存储到Book表中
    return HttpResponse('post OK')


@csrf_exempt
def test2(request):
    if request.method == 'GET':
        return HttpResponse("get OK")
    bookForm = BookForm(data=request.POST, files=request.FILES)
    if bookForm.is_valid():
        name = bookForm.cleaned_data.get('name')
        file = bookForm.cleaned_data.get('file')
        book = Book.objects.create(
            name=name,  file=file)  # 将数据存储到Book表中
    return HttpResponse('post OK')


@csrf_exempt
def uploadfile(request):
    if request.method == 'GET':
        return HttpResponse("get OK")
    form = SingleFileForm(data=request.POST, files=request.FILES)

    if form.is_valid():
        form.clean()
        model = form.save(commit=False)

        model.save()
        return JsonResponse(model)
    return JsonResponse(form.get_errors(), status=status.HTTP_506_VARIANT_ALSO_NEGOTIATES)


@csrf_exempt
def upload(request):

    for myfile in request.FILES.values():
        filename = get_unique_str()+'.'+myfile.name.split('.')[-1]
        # 文件路径
        filepath = os.path.join(settings.MEDIA_ROOT, filename)
        f = open(filepath, 'wb')
        for i in myfile.chunks():
            f.write(i)
        f.close()
        return JsonResponse({'url': settings.STATIC_URL+'uploads/'+filename, 'filename': filename})
    return HttpResponse("未上传文件")


@csrf_exempt
def lesson(request):
    if request.method == 'GET':
        name = request.GET.get('name', False)
        if name:
            files = File.objects.filter(name=name).order('-created_at')
            serializer = FileSerializer(files, many=True)
            return JsonResponse(serializer.data, status=status.HTTP_200_OK)
        return JsonResponse("get OK")
    if request.method == 'POST':
        lessonform = LessonForm(
            data=JSONParser().parse(request), files=request.FILES)
        if lessonform.is_valid():
            lesson = lessonform.save()
            serializer = LessonSerializer(lesson)
            return JsonResponse(serializer.data, status=status.HTTP_201_CREATED)

        return JsonResponse(lessonform.get_errors())

    return HttpResponse("ok ALL")


@csrf_exempt
def lesson_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        lessons = lesson.objects.all()
        serializer = LessonSerializer(lessons, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = LessonSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)


@csrf_exempt
def file_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        owner = request.GET.get('owner', False)
        if owner:
            files = File.objects.filter(
                owner=owner).order_by('-created_at')[:3]
            serializer = FileSerializer(files, many=True)
            return JsonResponse(serializer.data, status=201, safe=False)
        return JsonResponse([], safe=False)

    elif request.method == 'POST':
        serializer = FileSerializer(data=request.FILES)
        if serializer.is_valid():
            file = serializer.validated_data.get('file', False)
            if file:
                # from django.core.files.base import File
                # from django.core.files.uploadedfile.InMemoryUploadedFile import InMemoryUploadedFile
                from django.core.files.uploadedfile import InMemoryUploadedFile
                from django.core.files.uploadedfile import UploadedFile
                # print(type(file))
                # filepath = os.path.join(
                #     settings.MEDIA_ROOT, file.name)
                # serializer.validated_data['filesize'] = os.path.getsize(
                #     filepath)
                # kind = filetype.guess(filepath)
                # if kind != None:
                #     serializer.validated_data['extension'] = kind.extension
                #     serializer.validated_data['mime'] = kind.mime
                serializer.validated_data['size'] = file.size
                serializer.validated_data['content_type'] = file.content_type
                serializer.validated_data['filename'] = file.name
                serializer.validated_data['owner'] = request.POST.get(
                    'owner', '')
                serializer.save()

                return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)


@csrf_exempt
def file_detail(request):
    if request.method == 'GET':
        owner = request.GET.get('owner', False)
        if owner:
            files = File.objects.filter(
                owner=owner).order_by('-created_at')[:3]
            serializer = FileSerializer(files, many=True)
            return JsonResponse(serializer.data, status=201, safe=False)
        return JsonResponse([], safe=False)

    elif request.method == 'DELETE':
        return JsonResponse(serializer.errors, status=status.HTTP_200_OK)


@csrf_exempt
def docx(request):
    from .dagang7 import Section
    print(request.GET.get('file', False))
    sc = Section(None, r"d:\\专业选修课.docx",
                 'dagang7.json', 0, '文档')
    return HttpResponse("ok 1")
